package cn.xiongxf.org.service.impl;

import cn.xiongxf.basic.exception.BusinessException;
import cn.xiongxf.basic.service.impl.BaseServiceImpl;
import cn.xiongxf.basic.util.BaiduAiUtils;
import cn.xiongxf.basic.util.Md5Utils;
import cn.xiongxf.basic.util.StrUtils;
import cn.xiongxf.org.domain.Employee;
import cn.xiongxf.org.domain.Shop;
import cn.xiongxf.org.domain.ShopAuditLog;
import cn.xiongxf.org.domain.ShopDto;
import cn.xiongxf.org.mapper.EmployeeMapper;
import cn.xiongxf.org.mapper.ShopAuditLogMapper;
import cn.xiongxf.org.mapper.ShopMapper;
import cn.xiongxf.org.service.ShopService;
import cn.xiongxf.user.domain.Logininfo;
import cn.xiongxf.user.mapper.LogininfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements ShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 店铺入驻
     * @param shop
     */
    @Transactional
    @Override
    public void settlement(Shop shop) {
        // 商家入驻逻辑步骤：
        // 一：校验(前端js校验了后端也要校验，因为前端js校验可以跳过，不安全)
        // 1.每个参数的空值判断
        String name = shop.getName();
        String address = shop.getAddress();
        String tel = shop.getTel();
        String logo = shop.getLogo();
        if(StringUtils.isEmpty(name)){
            throw new BusinessException("数据不能为空");
        }
        // 2.两次密码一致性校验：在Employee中加一个comfirmPassword字段，然后判断是否与密码相等
        // 3.判断该店铺是否已入驻：店铺名 + 电话 + 地址
        Shop shopTemp = shopMapper.loadByNameAndAddress(shop);
        if (shopTemp != null){
            throw new BusinessException("该店铺已入驻，请直接登陆！忘记密码请找回密码");
        }
        // 4.百度AI智能审核：文本、图片
        if (!BaiduAiUtils.textCensor(name)){
            throw new BusinessException("店铺名称非法！！！");
        }
        //
        String imgUrl = new String("http://123.207.27.208" + logo);
        if (!BaiduAiUtils.imgCensor(imgUrl)){
            throw new BusinessException("店铺logo非法！！！");
        }

        // 二：入驻业务
        // 1.保存店铺管理员信息t_employee
        Employee admin = shop.getAdmin();
        // 获取并设置盐值、密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Psw = Md5Utils.encrypByMd5( admin.getPassword() + salt);
        admin.setSalt(salt);
        admin.setPassword(md5Psw);

        employeeMapper.save(admin);

        // 2.保存店铺信息t_shop
        System.out.println(admin.getId());
        shop.setAdmin_id(admin.getId());  // 获取自增主键
        shopMapper.save(shop);

        // 3.保存登陆信息t_logininfo
        //Logininfo logininfo = logininfoMapper.loadById(admin.getLogininfo_id());
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(admin,logininfo);
        logininfo.setType(0);  // 0-管理员
        logininfoMapper.save(logininfo);

        // 4.将shop_id、logininfo_id保存到t_employee中，更新
        admin.setShop_id(shop.getId());  // 获取自增id
        admin.setLogininfo_id(logininfo.getId());
        employeeMapper.update(admin);
    }

    /**
     * 店铺审核通过
     * @param log
     */
    @Transactional
    @Override
    public void auditPass(ShopAuditLog log) throws MessagingException {
        // 1.改状态
        Shop shop = shopMapper.loadById(log.getShopId());
        shop.setState(2);
        shopMapper.update(shop);

        // 2.添加审核日志
        log.setState(2);
        log.setAuditId(351L);
        shopAuditLogMapper.update(log);

        // 3.发送邮件：审核通过，点击激活
        MimeMessage mimeMessageessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessageessage, true, "UTF-8");
        // 发件人
        helper.setFrom("1229234469@qq.com");
        // 收件人
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        String email = employee.getEmail();
//        String email = shop.getAdmin().getEmail();  // 不可行，因为根据id从数据库中查到的shop只有admin_id,无admin对象
        helper.setTo(email);
        // 主题
        helper.setSubject("店铺激活邮件");
        // 正文
        helper.setText("<h1>您的店铺入驻成功！</h1><br>" +
                "<a href='http://localhost:8080/shop/active/"+shop.getId()+"'>点击链接激活</a>",true);
        // 发送
        javaMailSender.send(mimeMessageessage);
    }

    /**
     * 店铺审核驳回
     * @param log
     */
    @Transactional
    @Override
    public void auditReject(ShopAuditLog log) throws MessagingException {
        // 1.改状态
        Shop shop = shopMapper.loadById(log.getShopId());
        shop.setState(4);
        shopMapper.update(shop);

        // 2.添加审核日志
        log.setState(4);
        log.setAuditId(351L);
        shopAuditLogMapper.update(log);

        // 3.发送邮件：审核驳回，点击重新入驻
        MimeMessage mimeMessageessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessageessage, true, "UTF-8");
        // 发件人
        helper.setFrom("1229234469@qq.com");
        // 收件人
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());
        String email = employee.getEmail();
        helper.setTo(email);
        // 主题
        helper.setSubject("店铺入驻驳回邮件");
        // 正文
        helper.setText("<h1>您的店铺入驻失败！</h1><br>" +
                "<a href='http://localhost:8081/#/register'>点击链接重新入驻</a>",true);
        // 发送
        javaMailSender.send(mimeMessageessage);

        // 4.删除驳回的入驻信息
        // 删除管理员信息
        employeeMapper.remove(shop.getAdmin_id());
        // 删除店铺信息
        shopMapper.remove(shop.getId());
    }

    /**
     * 点击邮件激活
     * @param id
     */
    @Transactional
    @Override
    public void active(Long id) {
        Shop shop = shopMapper.loadById(id);
        shop.setState(3);
        shopMapper.update(shop);
    }

    @Override
    public List<ShopDto> getCountByState() {
        return shopMapper.getCountByState();
    }

    @Override
    public void patchAdd(List<Shop> shops) {
        shopMapper.patchSave(shops);
    }

}
